<?php
/**
 * 活动模型
 */
namespace Common\Model;

class EventsModel extends BaseModel{


    private static $eventInstance=null;
    public static function getEventInstance(){
        if(!self::$eventInstance){
            self::$eventInstance=M('e_events',null,DB_MAIN_CFG);
        }
        return self::$eventInstance;
    }

    private static $joinInstance=null;
    public static function getJoinInstance(){
        if(!self::$joinInstance){
            self::$joinInstance=M('e_events_join',null,DB_MAIN_CFG);
        }
        return self::$joinInstance;
    }


    private static $photoInstance=null;
    public static function getPhotoInstance(){
        if(!self::$photoInstance){
            self::$photoInstance=M('e_events_photo',null,DB_MAIN_CFG);
        }
        return self::$photoInstance;
    }
    
    //活动状态  用户对于活动的状态枚举
    const JOIN_STATUS_APPLY         = 1;//已报名
    const JOIN_STATUS_SELECTED      = 2;//已入选
    const JOIN_STATUS_UNSELECTED    = 3;//未入选
    const JOIN_STATUS_UNJOIN        = 4;//放鸽子
    const JOIN_STATUS_CANDIDATE     = 5;//候选
    const JOIN_STATUS_CANCELAPPLY   = 6;//取消报名


    //活动订单支付状态枚举
    const ORDER_PAY_STATUS_NORMAL   = 0;//没有支付
    const ORDER_PAY_STATUS_NEEDPAY  = 1;//需要支付
    const ORDER_PAY_STATUS_PAYEND   = 2;//已支付支付
    

    public static $userStatus = array(
        self::JOIN_STATUS_APPLY         =>'已报名',
        self::JOIN_STATUS_CANDIDATE     =>"候选",
        self::JOIN_STATUS_SELECTED      =>"已入选",
        self::JOIN_STATUS_UNSELECTED    =>"未入选",
        self::JOIN_STATUS_UNJOIN        =>"放鸽子",
        self::JOIN_STATUS_CANCELAPPLY   =>"取消报名",
    );

    const USER_STATUS_ORDER = '待支付';

    const APPLY_PAY_OUT_TIME = 300;//支付过期时间五分钟

    //跳转方式
    const JUMP_MODE_NO      = 0;//无跳转
    const JUMP_MODE_LIST    = 1;//列表页跳转
    const JUMP_MODE_DETAIL  = 2;//详情页跳转

    //作业提交状态
    const EVENTS_TASK_DO        =1;//已交作业
    const EVENTS_TASK_DONOT     =0;//未交作业

    //作业审核状态
    const EVENTS_TASK_STATUS_ON     =1;//通过
    const EVENTS_TASK_STATUS_OFF    =2;//不通过

    //报名or入选
    const EVENTS_APPLY_LIST     =1;//报名列表
    const EVENTS_SELECTED_LIST  =2;//入选列表


    //活动逻辑删除状态
    const EVENTS_STATUS_DEL     =1;//删除
    const EVENTS_STATUS_ON      =0;//正常

    public static $taskStatus = array(
        self::EVENTS_TASK_DO    => '已交作业',
        self::EVENTS_TASK_DONOT => '未交作业',
    );

    public static function getEventsPhoto($eid,$uid,$num=10){
        $where="1";
        if ($eid){
            $where .= " and eid={$eid}";
        }
        if ($uid){
            $where .= " and uid={$uid}";
        }
        return self::getPhotoInstance()->where($where)->limit($num)->getField("path",true);
    }


    /**
     * 获取活动列表
     * @param $uid 可选
     * @param $page 页码
     * @param $pageSize 每页记录数
     * @param int $channel 频道
     * @param $clientShow 展示渠道
     * @param int $type
     * @param int $eid
     * @param null $keyword
     * @return array
     * Author: Ricksun
     */
    public static function getEventsList($uid,$page,$pageSize,$channel = 0,$clientShow=CLIENT_SHOW_ALL,$type=0,$eid=0,$keyword=null){
        $dataSuccess = array('status'=>self::SUCCESS,'msg'=>'成功');
        $dataFailure = array('status'=>self::FAILURE,'msg'=>'无效参数');

        $userLevel = getLevelKv();
//      $contentType = getContentTypeKv();
        $channelType = getChannelKv(OBJ_TYPE_ACTIVITY);
        $eventsM = M("e_events",null,DB_MAIN_CFG);
        $eventsJoinM = M("e_events_join",null,DB_MAIN_CFG);

        $where = " 1 AND del = 0 AND beginShowTime < ".time();
        if($channel){
            $where .= " AND find_in_set('{$channel}',channel) ";
        }

        //展现客户端类型
        if($clientShow!=CLIENT_SHOW_ALL){
            $where .=" and find_in_set({$clientShow}, clientShow)";
        }

        if($type){
            $where .=" and contentType={$type}";
        }

        if($keyword){
            $where .=" and title like '%{$keyword}%'";
        }


        
        $dataSuccess['total'] = $eventsM->where($where)->count();//获取数据总条数
        $dataSuccess['page'] = max($page,1);//返回当前页
        $dataSuccess['totalPage'] = ceil($dataSuccess['total']/$pageSize);//总共页数
        $dataSuccess['nextPage'] = $dataSuccess['page'] >= $dataSuccess['totalPage'] ? 0 : 1;//是有有下一页
        $offset = ($dataSuccess['page']-1)*$pageSize;
        $nowTime = time();
        if($eid){
            $order = "id={$eid} DESC,orby DESC,applyStartTime DESC ";
        } else{
            $order = "orby DESC,applyStartTime DESC";
        }
        $list = $eventsM->field("*,CASE WHEN applyStartTime > {$nowTime} THEN 2 WHEN applyStartTime < {$nowTime} AND applyEndTime > {$nowTime} THEN 3 WHEN applyEndTime < {$nowTime} THEN 1 END as orby ")
             ->where($where)
             ->limit($offset,$pageSize)
             ->order($order)
             ->select();
        if($list){
            foreach ($list as $key => $val){
                $list[$key]['channelHtml'] = $channelType[$val['channel']];

                if($list[$key]['jumpMode']!=EventsModel::JUMP_MODE_NO){
                    $list[$key]['jumpURL']=U('index/jump?'.UtilsModel::buildJump(OBJ_TYPE_ACTIVITY,$val['id'],$list[$key]['jumpURL']));
                }


                //$list[$key]['applyCount'] = $eventsJoinM->where('eid='.$val['id'])->count();//获取活动所有参加人数
                $list[$key]['joinStatus'] = 0;
                $list[$key]['joinStatusHtml'] = '';
                $list[$key]['userLevelHtml'] = $val['userLevel'] ? $userLevel[$val['userLevel']] : '';
                $list[$key]['imgList'] = C('UPLOAD_RESOURCE_PREFIX').$val['imgList'];
                //判断是否有uid, 用户是否参加过
                if($uid){
                    $row = $eventsJoinM->field('status,isPay')->where("uid = $uid AND eid = ".$val['id']." AND del = 0")->find();
                    if($row){
                        $list[$key]['joinStatus'] = $row['status'];
                        $list[$key]['joinStatusHtml'] = self::$userStatus[$row['status']];
                        if($row['isPay'] == 1) $list[$key]['joinStatusHtml'] = self::USER_STATUS_ORDER;
                    }
                    unset($row);
                }
            }
        }
        $dataSuccess['data'] = $list;
        return $dataSuccess;
    }



    public static function changeAdjustHot($eventId,$adjustHot){
        return EventsModel::getEventInstance()->where(" id = '{$eventId}' ")->setField('hotAdjust',$adjustHot);
    }


    public static  function addHot($eventId){
        $raw=EventsModel::getEventInstance()->where(" id = '{$eventId}' ")->field('hot,hotAdjust')->find();
        if(!$raw){
            return false;
        }
        $editData=array('hot'=>$raw['hot']+1);
        if($raw['hotAdjust']<EVENT_HOT_LIMIT){
            $rand=rand(0,EVENT_HOT_STEP);
            $rand=min(EVENT_HOT_LIMIT-$raw['hotAdjust'],$rand);
            $editData['hotAdjust'] =$raw['hotAdjust']+$rand;
        }
        EventsModel::getEventInstance()->where(" id = '{$eventId}' ")->save($editData);
    }

    /**
     * 获取我的活动列表
     * uid 用户ID 必填
     * page 页码 必填 默认 1
     * pageSize 每页条数 可选 默认12
     * return "data": {
    "total": "12", //总条数
    "page": 1, //当前页
    "totalPage": 1, //总页数
    "nextPage": 0, //是有有下一页 1为有
    "item": [
    {
    "id": "10",
    "title": "去活动区活动活动多多动",
    "contentType": "11",
    "model": "filter",
    "imgList": "http://223.corp.soe-soe.com/swd_server//upload/2016-04-13/570e19a43e9af.jpg",
    "content": "<p>阿撒旦法师的发生的发撒旦法按时打发按时打发按时打发按时打发按时打发按时打发按时打发爱的身份爱的身份</p>",
    "addTime": "1460551414",
    "showListTime": "2016-03-02 周二",
    "beginShowTime": "1460699852",
    "startTime": "1460699852",
    "endTime": "1461909452",
    "applyStartTime": "1460699852",
    "applyEndTime": "1461823052",
    "userLevel": "2",
    "originalPrice": "0.00",
    "price": "0.00",
    "point": "0",
    "places": "22",
    "location": "开元名都",
    "uriCount": "0",
    "shareUri": "阿撒打算打算的阿斯顿按时打发按时打发阿达",
    "probability": "10.000",
    "relation": "pointMall",
    "relationId": "65",
    "discount": "0.00",
    "hot": "0",
    "typeHtml": "777777",
    "applyCount": "0",
    "joinStatus": 0,
    "joinStatusHtml": "",
    "userLevelHtml": "老枪"
    },
    ...  ]}
     * Author: Ricksun
     */
    public static function getMyEventsList($uid,$page,$pageSize,$type=0){
        $dataSuccess = array('status'=>self::SUCCESS,'msg'=>'成功');
        $dataFailure = array('status'=>self::FAILURE,'msg'=>'无效参数');

        if( !$uid ){
            $dataFailure['msg']='请指定用户';
            return $dataFailure;
        }


        $userLevel = getLevelKv();
        $eventsType = getContentTypeKv();

        $eventsM = M("e_events",null,DB_MAIN_CFG);
        $eventsJoinM = M("e_events_join",null,DB_MAIN_CFG);
        $where = " jo.uid = '{$uid}' AND e_events.del = 0 AND jo.del = 0 ";

        if($type){
            $where .=" and e_events.contentType={$type}";
        }

        $dataSuccess['total'] = $eventsM->join("join e_events_join as jo on jo.eid = e_events.id ")->where($where)->count();//获取数据总条数
        $dataSuccess['page'] = $page ? $page : 1;//返回当前页
        $dataSuccess['totalPage'] = ceil($dataSuccess['total']/$pageSize);//总共页数
        $dataSuccess['nextPage'] = $dataSuccess['page'] >= $dataSuccess['totalPage'] ? 0 : 1;//是有有下一页
        $offset = ($dataSuccess['page']-1)*$pageSize;
        $list = $eventsM->field(" e_events.*,jo.status,jo.isPay,jo.useVip ")
            ->join(" join e_events_join as jo on jo.eid = e_events.id ")
            ->where($where)->limit($offset,$pageSize)
            ->order(" startTime DESC ")->select();
        if($list){
            foreach ($list as $key => $val){
                $list[$key]['typeHtml'] = $eventsType[$val['contentType']];
                //$list[$key]['applyCount'] = $eventsJoinM->where('eid='.$val['id'])->count();//获取活动所有参加人数

                $list[$key]['joinStatus'] =  $val['status'];
                $list[$key]['joinStatusHtml'] = self::$userStatus[$val['status']];
                if ($val['status']==self::JOIN_STATUS_SELECTED && $val['useVip']==1){
                    $list[$key]['joinStatusHtml']="年卡入选";
                }


                if($val['isPay'] == 1) $list[$key]['joinStatusHtml'] = self::USER_STATUS_ORDER;
                $list[$key]['userLevelHtml'] = $val['userLevel'] ? $userLevel[$val['userLevel']] : '';
                $list[$key]['imgList'] = C('UPLOAD_RESOURCE_PREFIX').$val['imgList'];

                $list[$key]['firstEndTime'] = '';
                if($val['model'] == 'first' && $val['applyCount'] >= $val['places']){//获取先到先得 最后抢完的时间
                    $lastTime = $eventsJoinM->field('addTime')->where(" eid = {$val['id']} AND del = 0")->order(" addTime desc ")->find();
                    if($lastTime['addTime']-$val['applyStartTime'] > EVENT_FIRST_MAX_OVER_TIME){
                        $info['firstEndTime'] = '';
                    } else{
                        $list[$key]['firstEndTime'] = EventReadableTime($lastTime['addTime']-$val['applyStartTime']);
                    }
                }
            }
        }

        $dataSuccess['data'] = $list;
        return $dataSuccess;
    }

    /**
     * 获取活动详情
     * id 活动ID 必填
     * uid 用户ID 可选
     * return  "data": {
    "id": "10",
    "title": "去活动区活动活动多多动",
    "contentType": "11",
    "model": "filter",
    "imgList": "http://223.corp.soe-soe.com/swd_server//upload/2016-04-13/570e19a43e9af.jpg",
    "content": "<p>阿撒旦法师的发生的发撒旦法按时打发按时打发按时打发按时打发按时打发按时打发按时打发爱的身份爱的身份</p>",
    "addTime": "1460551414",
    "showListTime": "2016-03-02 周二",
    "beginShowTime": "1460699852",
    "startTime": "1460699852",
    "endTime": "1461909452",
    "applyStartTime": "1460699852",
    "applyEndTime": "1461823052",
    "userLevel": "2",
    "originalPrice": "0.00",
    "price": "0.00",
    "point": "0",
    "places": "22",
    "location": "开元名都",
    "uriCount": "0",
    "shareUri": "阿撒打算打算的阿斯顿按时打发按时打发阿达",
    "probability": "10.000",
    "relation": "pointMall",
    "relationId": "65",
    "discount": "0.00",
    "hot": "0",
    "joinMember": [],
    "joinMemberBe": [],
    "joinMemberBeCount": 0,
    "applyCount": 0,
    "typeHtml": "777777",
    "joinStatus": 0,
    "joinStatusHtml": "",
    "userLevelHtml": "老枪"
    }
     * Author: Ricksun
     */
    public static function getEventsInfo($id,$uid)
    {
        $dataSuccess = array('status'=>self::SUCCESS,'msg'=>'成功');
        $dataFailure = array('status'=>self::FAILURE,'msg'=>'无效参数');

        if( !$id ){
            $dataFailure['msg']='请指定活动';
            return $dataFailure;
        }
        $where = " id = '{$id}' AND del = 0 ";
        $userLevel = getLevelKv();
        $eventsType = getContentTypeKv();
        $eventsM = M("e_events",null,DB_MAIN_CFG);
        $eventsJoinM = M("e_events_join",null,DB_MAIN_CFG);
        $info = $eventsM->where($where)->find();

        if(!$info){
            $dataFailure['msg']='指定的活动不存在';
            return $dataFailure;
        }

        EventsModel::delApplyPayOutTimeStatus();//没有付钱的 过了五分钟(删除)

        $info['joinMember'] = $eventsJoinM->field('uid,status,nickname')->where(" eid = '{$id}' AND del = 0 AND status NOT IN(".self::JOIN_STATUS_CANCELAPPLY.")")->order(" addTime DESC ")->select();//获取活动所有参加人数
        if (strcasecmp($info['model'],"filter")==0 && $info['applyEndTime']>time()){
            $info['joinMemberBe'] = '';
            $info['joinMemberBeCount'] = 0;
        }
        else{
            $info['joinMemberBe'] = $eventsJoinM->field('uid,status,nickname')->where("eid = '{$id}' AND del = 0 AND status in(".self::JOIN_STATUS_SELECTED.",".self::JOIN_STATUS_UNJOIN.")")->order(" addTime DESC ")->select();//获取入选人
            $info['joinMemberBeCount'] = count($info['joinMemberBe']);
        }


        $info['typeHtml'] = $eventsType[$info['contentType']];
        $info['joinStatus'] = 0;
        $info['joinStatusHtml'] = '';
        $info['userLevelHtml'] = $info['userLevel'] ? $userLevel[$info['userLevel']] : '';
        $info['imgList'] = C('UPLOAD_RESOURCE_PREFIX').$info['imgList'];
        if($info['jumpMode']!=EventsModel::JUMP_MODE_NO){
            $info['jumpURL']=U('index/jump?'.UtilsModel::buildJump(OBJ_TYPE_ACTIVITY,$id,$info['jumpURL']));
        }

        $info['firstEndTime'] = '';
        if($info['model'] == 'first' && $info['applyCount'] >= $info['places']){//获取先到先得 最后抢完的时间
            $lastTime = $eventsJoinM->field('addTime')->where(" eid = {$id} AND del = 0")->order(" addTime desc ")->find();
            if($lastTime['addTime']-$info['applyStartTime'] > EVENT_FIRST_MAX_OVER_TIME){
                $info['firstEndTime'] = '';
            } else{
                $info['firstEndTime'] = EventReadableTime(max($lastTime['addTime']-$info['applyStartTime'],3));
            }
        }
        //判断是否有uid, 用户是否参加过
        if($uid){
            $row = $eventsJoinM->field('status,isPay,orderID,sharePic')->where("uid = {$uid} AND eid = {$id} AND del = 0")->find();
            if($row) {
                $info['sharePic']   = $row['sharePic'];
                $info['joinStatus'] = $row['status'];
                $info['joinStatusHtml'] = self::$userStatus[$row['status']];
                $info['isPay'] = 0;
                if($row['isPay'] == 1) {
                    $info['joinStatusHtml'] = self::USER_STATUS_ORDER;
                    $info['isPay'] = $row['orderID'];

                    $payOrderId = M("o_order",null,DB_MAIN_CFG)->where("uid={$uid} and objType=".OBJ_TYPE_ACTIVITY." and objID={$id}")->max('id');
                    $info['payUrl'] = './pay/paycenter.php?m=PayCenter&c=Order&a=pay&id='.$payOrderId;
                }
            }
            unset($row);
        }

        $dataSuccess['data'] = $info;
        return $dataSuccess;
    }


    /**
     * 获取活动详情（活动报名页面）
     * @param $id
     * @return array
     */
    public static function getEventDetail($id){
        $dataSuccess = array('status'=>self::SUCCESS,'msg'=>'成功');
        $dataFailure = array('status'=>self::FAILURE,'msg'=>'无效参数');

        if( !$id ){
            return $dataFailure;
        }
        $info = M("e_events",null,DB_MAIN_CFG)->where(" id = '{$id}' AND del = 0 ")->find();
        if(!$info){
            $dataFailure['msg']='指定的活动不存在';
            return $dataFailure;
        }
        $dataSuccess['data'] = $info;
        return $dataSuccess;
    }

    /**
     * 文章详情-关联活动
     * Author:wwl
     * @param:id
     * return array
     */
    public static function getArticleAboutEventInfo($id){
        $dataSuccess = array('status'=>self::SUCCESS,'msg'=>'成功');
        $dataFailure = array('status'=>self::FAILURE,'msg'=>'无效参数');
        if( !$id ){
            return $dataFailure;
        }

        $info = M("e_events",null,DB_MAIN_CFG)->where("id={$id}")->field("title,imgList,showListTime")->find();
//        $info['imgList'] = substr($info['imgList'],0,30)."210142/".substr($info['imgList'],37);
        $info['imgList'] = substr($info['imgList'],0,42)."210142/".substr($info['imgList'],49);
        $dataSuccess['data'] = $info;
        return $dataSuccess;
    }

    /**
     * 获取作业分享内容
     * eid 活动ID 必填
     * Author：wwl
     */
    public static function getTaskShare($eid){
        $taskM = M('e_events_task',null,DB_MAIN_CFG);
        $data = $taskM->where("eid={$eid} and status=".self::EVENTS_TASK_STATUS_ON)->select();
        if($data){
            $uid = array();
            foreach($data as $key => $val){
                $imgList = explode(',',$val['imgList']);
                $data[$key]['imgList'] = $imgList;

                $uid[] = $val['uid'];
            }
            $uidStr = implode(',',$uid);
            $userInfo = M('u_user_base',null,DB_MAIN_CFG)->where("uid IN ({$uidStr})")->field("uid,nickname")->select();
            foreach($data as $k=>$v){
                foreach($userInfo as $user){
                    if($user['uid'] == $v['uid']){
                        $data[$k]['nickname'] = $user['nickname'];
                        break;
                    }
                }
            }
        }
        return $data;
    }

    /**
     * 获取用户交作业情况
     * Author:wwl
     */
    public static function getUserTaskInfo($uid){
        $dataSuccess = array('status'=>self::SUCCESS,'msg'=>'成功');
        $dataFailure = array('status'=>self::FAILURE,'msg'=>'无效参数');
        $uid = intval($uid);
        if(!$uid) {
            $dataFailure['msg']='请先登录后操作';
            return $dataFailure;//参数错误,或者用户没有登录
        }
        $eidArr = M('e_events_join',null,DB_MAIN_CFG)->where("status=".self::JOIN_STATUS_SELECTED." and uid={$uid} and doTask=0")->getField("eid",true);
        $eidStr = implode(',',$eidArr);
        $data=null;
        if($eidArr){
            $time = time();
            $data = M('e_events',null,DB_MAIN_CFG)
                ->where("id in ({$eidStr}) and task=1 and endTime <= {$time}")
                ->order("endTime ASC")
                ->getField('title',true);
        }

        $dataSuccess['data'] = $data;
        return $dataSuccess;
    }



    public static function adjustApply($eid,$uid){
        $dataSuccess = array('status'=>self::SUCCESS,'msg'=>'成功');
        $dataFailure = array('status'=>self::FAILURE,'msg'=>'无效参数');

        $hasJoined=self::getJoinInstance()->where(" eid = '{$eid}' AND uid = '{$uid}' AND del = 0 AND status !=".self::JOIN_STATUS_CANCELAPPLY)->find();
        if($hasJoined){//用户已参加过
            $dataFailure['msg'] = '已参加过该活动,不可重复报名';
            return $dataFailure;
        }
        $uinfo=UserModel::getInstance()->where("uid={$uid}")->field("nickname,bindPhone,realName")->find();
        if (!$uinfo){
            $dataFailure['msg'] = '指定的用户不存在';
            return $dataFailure;
        }

        $insertdata = array('uid'=>$uid, 'nickname'=>$uinfo['nickname'], 'eid'=>$eid, 'objContentType'=>0 , 'addTime'=> time(), 'phone'=>$uinfo['bindPhone'], 'realName'=>$uinfo['realName'], 'mark'=>'');

        $einfo = self::getEventInstance()->where(" id = '{$eid}'")->field("model,places")->find();
        switch ($einfo['model']) {
            case 'filter'://官方筛选
                $insertdata['status'] = self::JOIN_STATUS_APPLY;
                break;
            default:
                $selectedUser = EventsModel::getJoinInstance()->where(" eid = '{$eid}' AND  status = '".EventsModel::JOIN_STATUS_SELECTED."' AND del = 0 ")->count();//获取已入选的人数
                if($einfo['places']>0 && $einfo['places']<= $selectedUser){
                    $insertdata['status'] = self::JOIN_STATUS_APPLY;
                }else{
                    $insertdata['status'] = self::JOIN_STATUS_SELECTED;
                }
                break;
        }
        EventsModel::getJoinInstance()->add($insertdata);
        self::getEventInstance()->where(" id = '{$eid}'")->setInc('applyCount');//增加报名人数
        return $dataSuccess;
    }


    /**
     * 提交报名
     * id 活动ID 必填
     * uid 用户ID 必填
     * phone 用户手机号 必填
     * realName 用户真实姓名 必填
     * return array('status'=> 1, 'msg'=>'手机号码格式错误') or array('status'=> 0, 'title'=>'恭喜您中奖了', 'text'=>'报名结果将第一时间在XXX公布')
     *          如果是 random 随机中奖 会多返回一个产品 array('status'=> 0, 'title'=>'恭喜您中奖了', 'text'=>'报名结果将第一时间在XXX公布', 'item'=> array('id'=>11,'title'=>'xxx兑换活动',) )
     * Author: Ricksun
     */
    public static function apply($id,$uid,$nickname,$phone,$realName,$mark,$babyNickname='',$babySex='',$babyBirthday='',$useVIP=0,$street='',$address='',$addressPool='',$otherPool='',$ext=''){
        $dataSuccess = array('status'=>self::SUCCESS,'msg'=>'成功');
        $dataFailure = array('status'=>self::FAILURE,'msg'=>'无效参数');
        
        $id = intval($id);
        $uid = intval($uid);
        $nickname = trim($nickname);
        $phone = strip_tags(trim($phone));
        $realName = strip_tags(trim($realName));
        $mark = strip_tags(trim($mark));

        if(!$uid || !$id) {
            $dataFailure['msg']='请指定用户及活动';
            return $dataFailure;//参数错误,或者用户没有登录
        }
        if(!filedPreMatch('phone', $phone)){
            $dataFailure['msg'] = '手机号码格式错误';
            return $dataFailure;
        }

        if(strlen($realName)<2 || strlen($realName)>18){
            $dataFailure['msg'] = '真实姓名格式错误';
            return $dataFailure;
        }

        if($mark && true !== $maskStr = checkCleanWord($mark) ){
            $dataFailure['msg'] = '留言中不能包含'.$maskStr;
            return $dataFailure;
        }

        $eventsM = self::getEventInstance();
        $eventsJoinM =self::getJoinInstance();
        EventsModel::delApplyPayOutTimeStatus();

        //提示之后是否 返回详情 0不动 1返回详情 2返回列表(考虑)
        $dataFailure['comeback'] = 0;
        $dataSuccess['comeback'] = 0;

        $hasJoined = $eventsJoinM->where(" eid = '{$id}' AND uid = '{$uid}' AND del = 0 AND status !=".self::JOIN_STATUS_CANCELAPPLY)->find();
        if($hasJoined){//用户已参加过
            $dataFailure['msg'] = '您已参加过该活动';
            $dataFailure['comeback'] = 1;
            return $dataFailure;
        }

        $info = $eventsM->where(" id = '{$id}'")->find();
        if ($info['needDeliver']!=0){
            if(!$street || !$address) {
                $dataFailure['msg'] = '请填写配送地址';
                return $dataFailure;
            }else{
                UserModel::getInstance()->where("uid={$uid}")->save(array('deliverArea'=>$street,'deliverAddress'=>$address));
            }
        }



        $userResult = UserModel::getUserChangeFul($uid);
        $user       = $userResult['data'];

        $countApply = $eventsJoinM->where(" eid = '{$id}' and status=".self::JOIN_STATUS_SELECTED)->count();

        $newtime = time();
        if($newtime > $info['applyEndTime']){
            $dataFailure['msg'] = '该活动已结束，请关注最新活动';
            return $dataFailure;
        }

        if($newtime < $info['applyStartTime']){
            $dataFailure['msg'] = '活动报名未开始，请稍后';
            return $dataFailure;
        }

        if(strlen($info['addressPool'])>0 && strlen($addressPool)<1){
            $dataFailure['msg'] = '必须选择一个地址';
            return $dataFailure;
        }



        //查看等级要求
        if($info['userLevel']>$user['level']){
            $dataFailure['msg'] = '您的等级不够啊！马上去升级';
            return $dataFailure;
        }

        //判断用户积分
        if($info['point'] && $info['point']>$user['point']){
            $dataFailure['msg'] = '您的积分不足，马上去赚积分';
            return $dataFailure;
        }



        if ($info['needNickname']==1){
            if(strlen($babyNickname)<1) {
                $dataFailure['msg'] = '本活动要求注明宝宝的昵称';
                return $dataFailure;
            }else{
                UserModel::getInstance()->where("uid={$uid}")->setField('babyNickname',$babyNickname);
            }
        }
        if ($info['needSex']==1){
            if(strlen($babySex)<1) {
                $dataFailure['msg'] = '本活动要求注明宝宝的性别';
                return $dataFailure;
            }else{
                UserModel::getInstance()->where("uid={$uid}")->setField('babySex',$babySex);
            }
        }

        if ($info['needAge']==1){
            if(strlen($babyBirthday)<7) {
                $dataFailure['msg'] = '本活动要求注明宝宝的出生年月';
                return $dataFailure;
            }else{
                UserModel::getInstance()->where("uid={$uid}")->setField('babyBirthday',$babyBirthday);
            }
        }


        $insertdata = array(
            'uid'=>$uid,
            'nickname'=>$nickname,
            'eid'=>$id,
            'objContentType'=>$info['contentType'] ,
            'addTime'=> $newtime,
            'phone'=>$phone,
            'realName'=>$realName,
            'mark'=>$mark,
            'babyNickname'=>$babyNickname,
            'babySex'=>$babySex,
            'babyBirthday'=>$babyBirthday,
            'street'=>$street,
            'address'=>$address,
            'addressPool'=>$addressPool,
            'otherPool'=>$otherPool,
            'ext'   =>$ext,
        );
        $insertid = 0;
        $dataSuccess['item'] = array();
        $dataSuccess['text'] = array();
        $dataSuccess['title'] = array();
        $dataSuccess['payUrl'] = '';//支付跳转
        //入选 标示
        switch ($info['model']){
            case 'filter'://官方筛选6
                $insertdata['status'] = self::JOIN_STATUS_APPLY;
                //取消报名后重新报名
                $applyAgain = $eventsJoinM->where(" eid = '{$id}' AND uid = '{$uid}' AND status= ".self::JOIN_STATUS_CANCELAPPLY)->find();
                if($applyAgain){
                    $eventsJoinM->where("id={$applyAgain['id']}")->save($insertdata);
                } else{
                    $insertid = $eventsJoinM->add($insertdata);
                }
                $dataSuccess['title'] = '报名成功！';
                //$dataSuccess['text'] = "报名结果将第一时间在".date("m月d日", ($info['applyEndTime']+86400) )."公布";//活动报名结束时间 加一天
                $dataSuccess['text'] = '';//活动报名结束时间 加一天
                $dataSuccess['comeback'] = 1;
                $dataSuccess['applyStatus'] = 1;//报名成功
                break;
            case 'first'://先到先得
                if($countApply>=$info['places']){
                    $dataSuccess['title'] = "未中奖！";
                    $dataSuccess['msg'] = '请关注我们的活动，再接再厉吧！';
                    $dataSuccess['comeback'] = 1;
                    $dataSuccess['applyStatus'] = 4;//未中奖,没有东西
                    return $dataSuccess;
                }
                $insertdata['status'] = self::JOIN_STATUS_SELECTED;
                $insertid = $eventsJoinM->add( $insertdata );
                $dataSuccess['comeback'] = 1;
                $dataSuccess['title'] = "恭喜您中奖了！";
                $dataSuccess['applyStatus'] = 2;//中奖成功
                break;
            case 'random'://随机中奖
                $probability = intval($info['probability']*1000);
                $mtrand = mt_rand(0,1000);
                $insertdata['status'] = self::JOIN_STATUS_UNSELECTED;
                $dataSuccess['comeback'] = 1;
                $dataSuccess['title'] = "很遗憾未中奖";
                $dataSuccess['text'] = "请关注我们的活动，再接再厉吧！";
                if($probability > $mtrand && $countApply<$info['places']){//中奖&&名额还有
                    $insertdata['status'] = self::JOIN_STATUS_SELECTED;
                    $dataSuccess['title'] = "恭喜您中奖了！";
                    $dataSuccess['text'] = "";
                    $dataSuccess['applyStatus'] = 2;//中奖成功
                }else{//未中奖 提示可以购买东西
                    if($info['relationId']) {
                        $preUploadUrl = C('UPLOAD_RESOURCE_PREFIX');
                        $dataSuccess['item'] = M($info['relation'], null, DB_MAIN_CFG)->field("id,titleInner as title,point,ceil(point*{$info['discount']}) as salePoint,concat('" . $preUploadUrl . "',listPic) as img,FORMAT({$info['discount']}*10,1) as discount,deliveryType")
                            ->where(" id = '{$info['relationId']}' ")->find();
                        $dataSuccess['applyStatus'] = 3;//未中奖,有东西
                    }else{
                        $dataSuccess['title'] = "未中奖！";
                        $dataSuccess['msg'] = '请关注我们的活动，再接再厉吧！';
                        $dataSuccess['comeback'] = 1;
                        $dataSuccess['applyStatus'] = 4;//未中奖,没有东西
                    }
                }
                $insertid = $eventsJoinM->add( $insertdata );
                break;
        }

        if($insertid){
            $eventsM->where(" id = '{$id}'")->setInc('applyCount');//增加报名人数
            if( ($info['price']*100) >0 ){
                $orderInsertid = OrderModel::buildOrder( array('uid'=>$uid, 'objType'=>OBJ_TYPE_ACTIVITY, 'objID'=>$info['id'], 'orderTitle'=>$info['title'], 'orderDesc'=>$mark, 'point'=>$info['point'], 'pay'=>$info['price'], 'marketPrice'=>$info['originalPrice'], 'userName'=>$realName, 'phone'=>$phone, 'payEndTime'=>time()+self::APPLY_PAY_OUT_TIME ) );
                $dataSuccess['payUrl'] = './pay/paycenter.php?m=PayCenter&c=Order&a=pay&id='.$orderInsertid;

                $eventsJoinM->where(" id = '{$insertid}'")->save( array('isPay'=>self::ORDER_PAY_STATUS_NEEDPAY, 'orderID'=>$orderInsertid));
            }
        }

        //判断用户积分
        if($info['point'] && ($info['price']*100)<=0){
            $tempR=UserModel::minusPoint($uid,-1,$info['point'],OPT_APPLY_EVENT,"{$info['id']}|{$info['title']}");
            $dataSuccess['ext']=$tempR['ext'];
        }

        if($mark){
            $uinfo = array(
                'uid'=>$uid,
                'nickname'=>$nickname,
            );
            $result=CommentModel::commentNew(2,$id,0,$mark,$uinfo,0);
        }

        if ($useVIP){
            $vipInfo=UserModel::getUserVipInfo($uid);
            if ($vipInfo['vipEndTime']>time() && $vipInfo['vipEventJoinTimes']>0){//未过期，且有次数

                $selectedUser = $eventsJoinM->where(" eid = '{$id}' AND  status = '".EventsModel::JOIN_STATUS_SELECTED."' AND del = 0 ")->count();//获取已入选的人数
                if($info['places']>0 && $info['places']<= $selectedUser){
                    $dataSuccess['msg'] = '入选名额已满';
                }else{
                    UserModel::getInstance()->where("uid={$uid}")->setDec("vipEventJoinTimes");
                    $eventsJoinM->where("eid={$id} and uid={$uid}")->save(array("status"=>self::JOIN_STATUS_SELECTED,"useVip"=>1));
                    $vipInfo['vipEventJoinTimes']--;
                    UserModel::getVipLogInstance()->add(array("uid"=>$uid,"addTime"=>time(),"act"=>"使用直接入选机会，剩余{$vipInfo['vipEventJoinTimes']}次"));
                    $dataSuccess['msg'] = '您已成功入选本次活动';
                }
            }

        }


        return $dataSuccess;
    }

    /**
     * 之后后更改订单状态
     * User: Rick.Sun.<sunwgjj@126.com>
     * Return: mixed
     * Address: 浙江宣逸网络科技有限公司
     * @param $id
     * @param $uid 付费用户
     * @param $objID 付费对象ID
     * @return mixed
     */
    public static function afterPay($id,$uid,$objID){
        return M("e_events_join",null,DB_MAIN_CFG)->where(" orderID={$id} and isPay = 1 ")->save( array('isPay'=>2 , 'del'=>0)  );
    }

    /**
     * 逻辑删除超时未支付报名记录
     * Author: shijy
     */
    public static function delApplyPayOutTimeStatus(){
        //没有付钱的 过了五分钟(删除)
        $lastFireTime = time()-self::APPLY_PAY_OUT_TIME;
        self::getJoinInstance()
            ->where(" addTime <= {$lastFireTime} AND isPay = 1 and del = 0")
            ->index('addtimePay')
            ->save( array('del'=>1) );
        // eid = '{$id}' AND addTime <= {$lastFireTime} AND isPay = 1
    }


    //取消报名
    public static function cancelRegistration($eid,$uid){
        $dataSuccess = array('status'=>self::SUCCESS,'msg'=>'成功');
        $dataFailure = array('status'=>self::FAILURE,'msg'=>'无效参数');

        if(!$eid || !$uid){
            return $dataFailure;
        }
        $res = self::getJoinInstance()->where("eid={$eid} and uid={$uid}")->save(array("status"=>self::JOIN_STATUS_CANCELAPPLY));
        if($res !== false){
            self::getEventInstance()->where("id={$eid}")->setDec("applyCount");   //报名人数-1;
            $point = self::getEventInstance()->where("id={$eid}")->getField("point");
            if($point>0){
                UserModel::plusPoint($uid,-1,$point,OPT_CANCEL_APPLY);
            }
            return $dataSuccess;
        } else{
            return $dataFailure;
        }

    }

    /**
     * 获取活动报名列表
     * $id 活动ID 必填
     * type 1|2 1报名 2已入选
     * page 页码 必填 默认 1
     * pageSize 每页条数 可选 默认12
     * return "data": {
    "total": "12", //总条数
    "page": 1, //当前页
    "totalPage": 1, //总页数
    "nextPage": 0, //是有有下一页 1为有
    "item": [
    {
    "uid": "10",
    "nickname": "sadd",
    },
    ...  ]}
     * Author: Ricksun
     */
    public static function getEventsApplyListLog($uid=0,$id,$type,$page,$pageSize){
        $dataSuccess = array('status'=>self::SUCCESS,'msg'=>'成功');
        $dataFailure = array('status'=>self::FAILURE,'msg'=>'无效参数');

        $eventsJoinM = self::getJoinInstance();

        $where = " e_events_join.eid = '{$id}' AND del = 0";
        if($type == self::EVENTS_SELECTED_LIST) {   //入选列表
            $where .= " AND e_events_join.status in(".self::JOIN_STATUS_SELECTED.",".self::JOIN_STATUS_UNJOIN.")";
        } elseif($type == self::EVENTS_APPLY_LIST){ //报名列表
            $where .= " AND e_events_join.status !=".self::JOIN_STATUS_CANCELAPPLY;
        }


        $dataSuccess['total'] = $eventsJoinM->where($where)->count();//获取数据总条数
        $dataSuccess['page'] = $page ? $page : 1;//返回当前页
        $dataSuccess['totalPage'] = ceil($dataSuccess['total']/$pageSize);//总共页数
        $dataSuccess['nextPage'] = $dataSuccess['page'] >= $dataSuccess['totalPage'] ? 0 : 1;//是有有下一页
        $offset = ($dataSuccess['page']-1)*$pageSize;

        $hasTask = M('e_events',null,DB_MAIN_CFG)->where("id={$id}")->getField("task");
        if($hasTask){
            $list = $eventsJoinM
                ->field("e_events_join.uid,nickname,e_events_join.status as eventStatus,e_events_task.status as taskStatus,CASE e_events_join.uid WHEN {$uid} THEN 1 END as flag")
                ->join("left join e_events_task on e_events_task.eid = e_events_join.eid and e_events_task.uid = e_events_join.uid")
                ->where($where)
                ->limit($offset,$pageSize)
                ->order("flag DESC,e_events_join.addTime DESC, e_events_join.id DESC ")
                ->select();
        } else{
            $list = $eventsJoinM->field("uid,nickname,status as eventStatus")
                ->where($where)
                ->limit($offset,$pageSize)
                ->order("addTime DESC, id DESC ")->select();
        }
        $dataSuccess['hasTask'] = $hasTask;
        $dataSuccess['data'] = $list;
        return $dataSuccess;
    }

    /**
     * 读取作业
     * $id e_events_task 作业编号
     */
    public static function getTask($eid,$uid){
        $data = M('e_events_task',null,DB_MAIN_CFG)->where("eid={$eid} and uid={$uid}")->field("content,imgList")->find();
        return $data;
    }
    /**
     * 保存/更新 作业
     */
    public static function saveTask($uid,$eid,$content,$imgList){
        $dataSuccess = array('status'=>self::SUCCESS,'msg'=>'成功');
        $dataFailure = array('status'=>self::FAILURE,'msg'=>'无效参数');
        if(!$uid || !$eid){
            return $dataFailure;
        }
        $taskM = M('e_events_task',null,DB_MAIN_CFG);
        $data = array(
            'uid'       => $uid,
            'eid'       => $eid,
            'content'   => $content,
            'imgList'   => $imgList,
            'addTime'   => time(),
            'status'    => self::EVENTS_TASK_STATUS_ON,
        );
        if($taskM->where("eid={$eid} and uid={$uid}")->find()){
            $res = $taskM->where("eid={$eid} and uid={$uid}")->save($data);
            if($res !== false){
                return $dataSuccess;
            } else{
                $dataFailure['msg']="作业更新失败，请稍后重试";
                return $dataFailure;
            }
        } else{
            $res = $taskM->add($data);
            if($res){
                M('e_events_join',null,DB_MAIN_CFG)->where("eid={$eid} and uid={$uid}")->setField("doTask",self::EVENTS_TASK_DO);
                return $dataSuccess;
            } else{
                $dataFailure['msg'] = "作业保存失败，请稍后重试";
                return $dataFailure;
            }
        }
    }

}